package vip.specimen.system.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.alibaba.fastjson.JSONObject;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * *@Author: 余浪人
 * *@Date：2021/2/4 17:47
 * *@Email:yulangren520@Gmail.com
 * *@QQ:1368419640
 **/
public class CommonUtil {

    /**
     * 验证手机号码
     *
     * @param phone 手机号码
     * @return 验证结果   null --> 合格
     */
    public static boolean phone(String phone) {
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$";
        phone = null != phone ? phone : "";
        return Pattern.compile(regex).matcher(phone).matches();
    }

    /**
     * 验证邮箱是否合法
     *
     * @param email email
     * @return 结果   null --> 合格
     */
    public static boolean email(String email) {
        String regex = "[a-zA-Z0-9_]+@[a-zA-Z0-9_]+(\\.[a-zA-Z0-9]+)+";
        email = null != email ? email : "";
        return Pattern.compile(regex).matcher(email).matches();
    }

    /**
     * 获取指定日期的时间
     *
     * @param futureType 是否 未来时间
     * @param isMonth    是否  月
     * @param num        数
     * @return 目标时间戳
     */
    @SuppressWarnings("all")
    public static long getAssignTime(boolean futureType, boolean isMonth, int num) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        if (true != isMonth) {
            if (true == futureType) {
                c.add(Calendar.DATE, +num);
            } else {
                c.add(Calendar.DATE, -num);
            }
        } else {
            if (true == futureType) {
                c.add(Calendar.MONTH, +num);
            } else {
                c.add(Calendar.MONTH, -num);
            }
        }
        return c.getTimeInMillis();
    }

    /**
     * 获取指定日期的时间
     *
     * @param futureType 是否 未来时间
     * @param isMonth    是否  月
     * @param num        数
     * @return 数据 --> 数组
     */
    public static LinkedHashMap getAssignTimeEvery(boolean futureType, boolean isMonth, int num) {
        long time = CommonUtil.getAssignTime(futureType, isMonth, num);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        long param[] = new long[]{time, System.currentTimeMillis()};
        Arrays.sort(param);
        Calendar start = Calendar.getInstance();
        start.setTimeInMillis(param[0]);
        Calendar end = (Calendar) start.clone();
        end.setTimeInMillis(param[param.length - 1]);
        LinkedHashMap list = new LinkedHashMap<String, Long>();
        while (start.before(end)) {
            list.put(format.format(start.getTime()), start.getTimeInMillis());
            start.add(Calendar.DAY_OF_YEAR, 1);
        }
        return list;
    }

    /**
     * 获取真实的IP地址
     *
     * @param request 请求
     * @return IP
     */
    public static String getIp(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    try {
                        ipAddress = InetAddress.getLocalHost().getHostAddress();
                    } catch (UnknownHostException e) {
//
                    }

                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) {
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }
        return ipAddress;
    }

    /**
     * 字符串=>md5加密
     *
     * @param str 明文 字符串
     * @return 密文
     */
    public static String stringToMd5(String str) {
        String newStr = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            BASE64Encoder base64e = new BASE64Encoder();
            newStr = base64e.encode(md5.digest(str.getBytes()));
        } catch (NoSuchAlgorithmException e) {
            System.out.println(e.getMessage());
        }
        return newStr;
    }

    /**
     * 获取
     *
     * @param request
     * @return
     */
    public static JSONObject pageParams(HttpServletRequest request) {
        JSONObject json = new JSONObject(2);
        Pattern pattern = Pattern.compile("^[0-9]*$");
        String pageStr = request.getParameter("page");
        String pageSizeStr = request.getParameter("pageSize");
        pageStr = null != pageStr ? pageStr : "0";
        pageSizeStr = null != pageSizeStr ? pageSizeStr : "0";
        int page = pattern.matcher(pageStr).matches() ? Integer.valueOf(pageStr) : 0;
        int pageSize = pattern.matcher(pageSizeStr).matches() ? Integer.valueOf(pageSizeStr) : 20;   // 不传默认size 为 20
        page = page < 0 ? 0 : page;
        pageSize = pageSize < 1 || pageSize > 100 ? 20 : pageSize;  // size 最大为100条
        json.put("page", page);
        json.put("pageSize", pageSize);
        return json;
    }

    /**
     * 字符串数组转字符串
     *
     * @param strArr 数组
     * @return 字符串
     */
    public static String convertArrayToString(String[] strArr) {
        if (null == strArr || strArr.length == 0) return "";
        String res = ""; //TODO优化字符串拼节
        for (int i = 0, len = strArr.length; i < len; i++) {
            res += strArr[i];
            if (i < len - 1) res += ",";
        }
        return res;
    }
}